<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" class="nav">
      <el-breadcrumb-item to="/welcome"
        ><strong>首页</strong></el-breadcrumb-item
      >
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品 </el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert
        center
        title="添加商品信息"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 20px"
        size="small"
      >
      </el-alert>

      <el-steps
        :space="200"
        align-center
        :active="activeIndex - 0"
        finish-status="success"
        size="14"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品信息"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!--左侧进度条-->
      <el-form
        :model="goodsfrom"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          class="tabs"
          v-model="activeIndex"
          :tab-position="tabPosition"
          style="height: 800px"
          @tab-click="tabclick"
          :before-leave="beforeTabLeave"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsfrom.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="text" v-model="goodsfrom.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsfrom.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsfrom.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="goodsfrom.goods_cat"
                :options="list"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品信息">
            <el-form-item v-for="item in goodsManylist" :key="item.attr_id"
              >{{ item.attr_name }}{{ item.attr_id }}
              <el-checkbox-group border v-model="item.attr_vals">
                <el-checkbox
                  border
                  v-for="(item, index) in item.attr_vals"
                  @change="change"
                  :key="index"
                  :label="item"
                  >{{ item }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item v-for="item in goodsOnlylist" :key="item.attr_id"
              >{{ item.attr_name }}
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              class="upload-demo"
              action="http://vue-shop-api-t.itheima.net/api/private/v1/upload"
              :headers="{
                Authorization: headers,
              }"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件,且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <quillEditor
              v-model="goodsfrom.goods_introduce"
              class="ql-editor"
            ></quillEditor>
            <el-button
              @click="submitForm('ruleForm')"
              class="submit"
              type="primary"
            >
              添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { getToken } from '@/utils/storage'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { GetGoodListApi, goodsprop, addgoods } from '@/api/goods'
export default {
  name: '',
  components: { quillEditor },
  data () {
    return {
      fileList: [],
      list: [],
      goodsManylist: [],
      goodsOnlylist: [],
      tabPosition: 'left',
      activeIndex: '',
      goodsfrom: { // 添加商品表单数据
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        goods_introduce: ''
      },
      rules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品类型', trigger: 'blur' }]
      },
      attrs: [],
      //图片上传的请求头
      headers: getToken()
    }
  },
  created () {
    this.getgoodslist()
  },
  computed: {
  },
  methods: {
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 次级选择器选项变化会触发这个函数
    handleChange (value) {
      if (this.goodsfrom.goods_cat.length < 3) {
        this.goodsfrom.goods_cat = []
      }
      console.log(value)
    },
    async getgoodslist () {
      const res = await GetGoodListApi()
      console.log(res, '获取-商品分类列表')
      this.list = res.data
    },
    // tabs切换时触发
    async tabclick () {
      // console.log(this.activeIndex);
      if (this.activeIndex === '1') {
        console.log(this.goodsfrom.goods_cat[2])
        const res = await goodsprop(this.goodsfrom.goods_cat[2], 'many')
        res.data.forEach(item => {
          item.attr_vals === '' ? item.attr_vals = [] : item.attr_vals = item.attr_vals.split(' ')
        })
        console.log(res.data, '动态获取值')
        this.goodsManylist = res.data
      } else if (this.activeIndex === '2') {
        const res = await goodsprop(this.goodsfrom.goods_cat[2], 'only')
        console.log(res, '静态获取值')
        this.goodsOnlylist = res.data
      }
    },

    change () {
      console.log(this.goodsManylist)
    },
    // 添加商品
    submitForm () {
      this.$refs.ruleForm.validate(async (valid) => {
        // console.log(this.resetForm);
        // valid是布尔值,只要有一个条件不满足就返回false
        if (valid) {
          const newFrom = JSON.parse(JSON.stringify(this.goodsfrom))
          newFrom.goods_cat = newFrom.goods_cat.join(',')
          console.log(this.goodsManylist)
          // 动态参数循环
          this.goodsManylist.forEach(item => {
            const obj = {
              attr_id: item.attr_id,
              attr_value: (item.attr_vals).join(',')
            }
            this.attrs.push(obj)
          })
          // 静态属性循环
          this.goodsOnlylist.forEach(item => {
            const obj = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            this.attrs.push(obj)
          })
          console.log(this.attrs, 9999)
          // 发送添加请求
          console.log(newFrom, '表单内容')
          const res = await addgoods(newFrom, this.attrs)
          this.$message.success('添加商品成功')
          this.$router.push('/goods')
          console.log(res)
        } else {
          // 不满足则提示用户输入
          this.$message.error('请填写表单值')
          return false
        }
      })
    },
    // 阻止tavs标签切换
    beforeTabLeave (activeName, nextName) {
      if (nextName === '0' && this.goodsfrom.goods_cat.length < 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    }

  }
}
</script>
<style lang='less'  scoped>
.tabs {
  margin-top: 20px;
}

.ql-editor {
  height: 300px;
}
.el-step__title {
  font-size: 20px;
}
.nav {
  font-size: 12px;
  margin-bottom: 15px;
}
.box-card {
  height: 800px;
}
</style>
